//  https://leetcode-cn.com/problems/3sum-closest
//  AcceptThreeCountSum.swift
//  LeetCodeSwift
//
//  Created by XFB on 2019/7/29.
//  Copyright © 2019 XFB. All rights reserved.
//  最接近的三数之和 【 时间复杂度 O(N^2) 空间复杂度 O(nC3) 】

import Foundation

class AcceptThreeCountSum {
    
    /**
     给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数，使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
     例如，给定数组 nums = [-1，2，1，-4], 和 target = 1.
     与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
     */
    
    /// 二分法循环
    func threeSumClosest(_ nums: [Int], _ target: Int) -> Int {
     
        if nums.count == 0 {
            return 0
        }
        
        /// 最小差异
        var minDiff = Int.max
        var sortedNums = nums.sorted(by: <)
        
        for i in 0 ..< sortedNums.count - 2 {
     
            let twoSum = target - sortedNums[i]
            var left = i + 1
            var right = sortedNums.count - 1
            
            while left < right {
                
                let diff = sortedNums[left] + sortedNums[right] - twoSum

                /// 差距
                if abs(diff) < abs(minDiff) {
                    minDiff = diff
                }
                
                if diff == 0 {
                    return target
                } else if diff > 0 {
                    repeat {
                        right = right - 1
                    } while left < right && nums[right] == nums[right + 1]
                } else if diff < 0 {
                    repeat {
                        left = left + 1
                    } while left < right && nums[left] == nums[left - 1]
                }
            
            }
        }
        
        return target + minDiff
    }
}
